package com.asman.vr

import android.media.MediaRecorder
import android.os.CountDownTimer
import android.view.View
import com.asman.base.lib.utils.PermissionUtils
import log

/**
 * @author ybk
 * @date :2020-01-17 15:44
 * @desc:
 */

class RecorderUtil(val maxSecond: Long) {

    private var mRecorder: MediaRecorder? = null

    lateinit var countDownTimer: CountDownTimer

    var filePath = ""//录音的文件路径

    init {
        countDownTimer = object : CountDownTimer(maxSecond, 100) {
            override fun onFinish() {
                countDownTimer.cancel()
            }

            override fun onTick(millisUntilFinished: Long) {
            }
        }
    }

    /**
     * 正在录音 ---录音中
     */
    // todo 这个方法要转 activity 作为参数
    // fun start(activity: BaseActivity, callBack: ((realStarted: Boolean) -> Unit)?) {
    fun start(view: View, callBack: ((realStarted: Boolean) -> Unit)?) {
        //先停止
        /*stopRecord()
        PermissionUtils.requestAudio(
            activity,
            object : PermissionUtils.OnPermissionListener() {
                override fun success() {
                    if (mRecorder == null) {
                        mRecorder = MediaRecorder()
                        mRecorder?.setAudioSource(MediaRecorder.AudioSource.MIC)
                        //todo 试试下面注释的两个格式  https://cloud.tencent.com/developer/article/1524531
                        mRecorder?.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)//AMR_NB
                        mRecorder?.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)//DEFAULT
                        mRecorder?.setAudioSamplingRate(8000)
                    }
                    filePath = "${activity.cacheDir}/${System.currentTimeMillis()}.mp3"
//                    filePath = "/storage/emulated/0/tencent/micromsg/download/录音测试.mp3"
                    mRecorder?.setOutputFile(filePath)
                    log("-----filepath--${filePath}")
                    mRecorder?.prepare()
                    mRecorder?.start()
                    countDownTimer.start()
                    callBack?.invoke(true)//获取权限成功正真开始录音啦
                }
            })*/
    }

    /**
     * 释放录音组件
     */
    fun stopRecord(): String {
        destroy()
        return filePath
    }

    //销毁
    fun destroy() {
        try {
            countDownTimer.cancel()
            if (mRecorder != null) {
                try {
                    mRecorder?.stop()
                } catch (e: IllegalStateException) {
                    // 如果当前java状态和jni里面的状态不一致，
                    mRecorder = null
                    mRecorder = MediaRecorder()
                }
                mRecorder?.release()
                mRecorder = null
            }
        } catch (e: Exception) {

        }
    }
}